<?php

namespace Whf\LazyBrick\Console;

use Illuminate\Console\GeneratorCommand;
use Whf\LazyBrick\Traits\ModelTrait;

class ServiceCommand extends GeneratorCommand
{
    use ModelTrait;
    /**
     * The name and signature of the console command.
     * @var string
     */
    protected $signature = 'lb:make_s {name}
        {--model=}
        {--module=}
        {--stub=}
        {--force=}
        {--namespace=}';

    /**
     * 后台模块场景分类比较切合，所以默认为Backend
     * 定义生成的 控制器 所在模块位置
     * @var string
     */
    protected $module = "";
    protected $servicePath = "";

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'make service';

    /**
     * @var ResourceGenerator
     */
    protected $generator;

    private function configInit(){
        $this->servicePath = config("lazy-brick.namespace.service");
        $this->module = config("lazy-brick.module.service");
    }


    /**
     * Execute the console command.
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:14
     * @return bool|void|null
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function handle()
    {
        $this->configInit();
        $modelName = $this->option('model');
        $modelName = $this->formatModelName($modelName);
        if(!$this->modelExists($modelName))
            return $this->error("Model not exists...");

        $this->generator = new ResourceGenerator($modelName);
        $name = $this->qualifyClass($this->getNameInput());
        $path = $this->getPath($name);

        //如果文件已存在,+ force 会覆盖原文件
        if ((! $this->hasOption('force') ||
                ! $this->option('force')) &&
            $this->alreadyExists($this->getNameInput())) {
            $this->error($this->getNameInput().' already exists!');
            return false;
        }
        $this->makeDirectory($path);

        $this->files->put($path, $this->buildClass($name));

        $this->info($this->type.' created successfully.');
    }

    /**
     * Get the default namespace for the class.
     * 重写父类的方法，当父类中调用$this->getDefaultNamespace()会执行此函数
     * 编辑器ctrl+左键 会指向父类的方法 要注意
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:03
     * @param string $rootNamespace
     * @return array|bool|string|null
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        if ($namespace = $this->option('namespace')) {
            return $namespace;
        }
        return $this->servicePath."\\".$this->module;
    }

    /**
     * Replace the namespace for the given stub.
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:14
     * @param string $stub
     * @param string $name
     * @return $this|GeneratorCommand
     */
    protected function replaceNamespace(&$stub, $name)
    {
        $stub = str_replace(
            ['DummyNamespace','DummyModelNamespace'],
            [$this->getNamespace($name),$this->getModelNamespace()],
            $stub
        );
        return $this;
    }

    protected function getModelNamespace(){
        return $this->formatModelName($this->option('model'));
    }

    /**
     * Get the stub file for the generator.
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:15
     * @return array|bool|string|null
     */
    protected function getStub()
    {
        if($stub = $this->option('stub')){
            return $stub;
        }
        if($this->option('model')){
            return __DIR__."/stubs/service.stub";
        }
        return __DIR__."/stubs/blank.stub";
    }

    /**
     * 替换其它块内容
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:15
     * @param string $stub
     * @param string $name
     * @return mixed|string
     */
    protected function replaceClass($stub, $name){

        return str_replace([
            'DummyClass',
            'DummyCondition',
            'DummyAdd',
            'DummyUpdate',
            'DummyModelName',
        ],
        [
            str_replace($this->getNamespace($name).'\\', '', $name),
            $this->indentCodes($this->generator->generateCondition()),
            $this->indentCodes($this->generator->generateAdd(),3),
            $this->indentCodes($this->generator->generateUpdate(),3),
            basename($this->getModelNamespace()),

        ],
        $stub
        );
    }

    /**
     * 配置左侧间距，我喜欢用制表符，默认2个
     * @author whf <wuhangfei1314@163.com>
     * @date 2019/12/16 23:06
     * @param $code
     * @param $multiplier
     * @return string
     */
    protected function indentCodes($code,$multiplier=2){
        $indent = str_repeat("\t", $multiplier);
        return rtrim($indent.preg_replace("/\r\n/","\r\n{$indent}",$code));
    }

}
